package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.domain.customer.CustomerDO;
import com.qk.dto.customer.CustomerDTO;
import com.qk.dto.customer.UpdateCustomerDTO;
import com.qk.entity.Customer;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.service.CustomerService;
import com.qk.vo.customer.CustomerListVO;
import com.qk.vo.customer.CustomerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author: Enid
 * @date: 2025/10/20 13:38
 * @description:
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public void updateCustomer(UpdateCustomerDTO dto) {
        Customer customer = BeanUtil.copyProperties(dto, Customer.class);
        customer.setUpdateTime(LocalDateTime.now());
        this.updateById(customer);
    }



    @Override
    public CustomerListVO selectById(Integer id) {
        Customer customer = customerMapper.selectById(id);
        return BeanUtil.copyProperties(customer, CustomerListVO.class);
    }

    @Override
    public void insert(CustomerDO customerDO) {
        if (ObjectUtil.isEmpty(customerDO.getPhone())|| ObjectUtil.isEmpty(customerDO.getName())){
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Customer customer = BeanUtil.toBean(customerDO, Customer.class);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customer.setBusinessId(null);
        customerMapper.insert(customer);
    }

    @Override
    public PageResult<CustomerVO> pageList(CustomerDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<CustomerVO> page = (Page<CustomerVO>) customerMapper.pageList(dto);
        return PageResult.<CustomerVO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
